package com.nantong.admin.controller;

import com.nantong.admin.annotation.PermissionRegister;
import com.nantong.admin.domain.SysUser;
import com.nantong.admin.service.ISysUserService;
import com.nantong.admin.util.LoginHelper;
import com.nantong.common.core.domain.R;
import com.nantong.common.core.exception.ServiceException;
import com.nantong.common.core.utils.StringUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * 个人中心
 *
 * @author nantong
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/api/system/profile")
@Tag(name = "个人中心", description = "个人中心相关接口")
@PermissionRegister(
    name = "个人中心", 
    key = "profile", 
    type = 2,  // 2=菜单
    path = "/profile",
    component = "/views/Profile/ProfileView.vue",
    icon = "user",
    sortOrder = 2
)
public class ProfileController {

    private final ISysUserService userService;
    
    @Value("${file.upload.path}")
    private String uploadPath;
    
    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    /**
     * 获取个人信息
     */
    @GetMapping
    @Operation(summary = "获取个人信息", description = "获取当前登录用户个人信息")
    public R<SysUser> getProfile() {
        Long userId = LoginHelper.getUserId();
        SysUser user = userService.getById(userId);
        return R.ok(user);
    }

    /**
     * 更新个人信息
     */
    @PutMapping
    @Operation(summary = "更新个人信息", description = "更新当前登录用户个人信息")
    public R<Void> updateProfile(@RequestBody SysUser user) {
        Long userId = LoginHelper.getUserId();
        user.setUserId(userId);
        userService.updateById(user);
        return R.ok();
    }

    /**
     * 修改密码
     */
    @PutMapping("/updatePassword")
    @Operation(summary = "修改密码", description = "修改当前登录用户密码")
    public R<Void> updatePassword(@RequestParam String oldPassword, @RequestParam String newPassword) {
        // 参数校验
        if (StringUtils.isEmpty(oldPassword)) {
            throw new ServiceException("原密码不能为空");
        }
        if (StringUtils.isEmpty(newPassword)) {
            throw new ServiceException("新密码不能为空");
        }
        if (newPassword.length() < 6) {
            throw new ServiceException("新密码长度不能少于6位");
        }
        
        // 获取当前登录用户
        Long userId = LoginHelper.getUserId();
        SysUser user = userService.getById(userId);
        if (user == null) {
            throw new ServiceException("用户不存在");
        }
        
        // 验证原密码
        if (!passwordEncoder.matches(oldPassword, user.getPassword())) {
            throw new ServiceException("原密码错误");
        }
        
        // 加密新密码
        String encodedPassword = passwordEncoder.encode(newPassword);
        
        // 更新密码
        user.setPassword(encodedPassword);
        userService.updateById(user);
        
        log.info("用户 {} 修改密码成功", user.getUserName());
        return R.ok("密码修改成功");
    }

    /**
     * 上传头像
     */
    @PostMapping("/uploadAvatar")
    @Operation(summary = "上传头像", description = "上传用户头像文件")
    public R<String> uploadAvatar(@RequestParam("file") MultipartFile file) {
        // 参数校验
        if (file == null || file.isEmpty()) {
            throw new ServiceException("请选择要上传的文件");
        }
        
        // 校验文件类型
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null) {
            throw new ServiceException("文件名不能为空");
        }
        
        String extension = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();
        if (!extension.matches("jpg|jpeg|png|gif|bmp|webp")) {
            throw new ServiceException("只支持上传JPG、PNG、GIF、BMP、WEBP格式的图片");
        }
        
        // 校验文件大小（2MB）
        if (file.getSize() > 2 * 1024 * 1024) {
            throw new ServiceException("图片大小不能超过2MB");
        }
        
        try {
            // 创建上传目录（按日期分类，格式：yyyyMMdd）
            String dateDir = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
            String uploadDir = uploadPath + File.separator + dateDir;
            Path dirPath = Paths.get(uploadDir);
            if (!Files.exists(dirPath)) {
                Files.createDirectories(dirPath);
            }
            
            // 生成唯一文件名
            String fileName = UUID.randomUUID().toString().replace("-", "") + "." + extension;
            Path filePath = dirPath.resolve(fileName);
            
            // 保存文件
            file.transferTo(filePath.toFile());
            
            // 返回相对路径（nginx会代理这个路径）
            String avatarUrl = "/srv/upload/" + dateDir + "/" + fileName;
            
            log.info("用户 {} 上传头像成功，保存路径: {}", LoginHelper.getUserId(), filePath);
            return R.ok("头像上传成功", avatarUrl);
            
        } catch (IOException e) {
            log.error("上传头像失败", e);
            throw new ServiceException("上传头像失败：" + e.getMessage());
        }
    }

    /**
     * 更新头像
     */
    @PutMapping("/avatar")
    @Operation(summary = "更新头像", description = "更新当前登录用户头像URL")
    public R<String> updateAvatar(@RequestParam String avatarUrl) {
        // 参数校验
        if (StringUtils.isEmpty(avatarUrl)) {
            throw new ServiceException("头像URL不能为空");
        }
        
        // 获取当前登录用户
        Long userId = LoginHelper.getUserId();
        SysUser user = userService.getById(userId);
        if (user == null) {
            throw new ServiceException("用户不存在");
        }
        
        // 更新头像URL
        user.setAvatar(avatarUrl);
        userService.updateById(user);
        
        log.info("用户 {} 更新头像成功: {}", user.getUserName(), avatarUrl);
        return R.ok("头像更新成功", avatarUrl);
    }
}
